package im.rtx.base.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * XML操作类 读取/写入/获取值/写入值
 * <p/>
 * Project  : iqq
 * Author   : 承∮诺 < 6208317@qq.com >
 * Created  : 14-4-16
 * License  : Apache License 2.0
 */
public class XmlUtils {

    /**
     * 获取XML节点的值
     *
     * @param doc
     * @param key
     * @return
     * @throws DocumentException
     */
    public static String getNodeText(Document doc, String key) {
        return doc.getRootElement().selectSingleNode(key).getText();
    }


    /**
     * 写入数据到XML
     *
     * @param doc
     * @param key
     * @param value
     */
    public static void setNodeText(Document doc, String key, String value){
        Element rootElement = doc.getRootElement();
        Node node = rootElement.selectSingleNode(key);
        if (node == null) {
            node = rootElement.addElement(key);
        }
        node.setText(value);
    }


    /**
     * 读入XML文件
     *
     * @param in
     * @return
     * @throws DocumentException
     */
    public static Document readXml(InputStream in) throws DocumentException {
        // 创建SAXReader读取器
        SAXReader saxReader = new SAXReader();
        // 读取xml
        Document document = saxReader.read(in);
        // 放到缓存中
        return document;
    }


    /**
     * 写入XML文件
     *
     * @param document
     * @param out
     * @throws java.io.IOException
     */
    public static void writeXml(OutputStream out, Document document) throws IOException {
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();// 设置XML文档输出格式
        outputFormat.setEncoding("UTF-8");// 设置XML文档的编码类型
        outputFormat.setIndent(true);// 设置是否缩进
        outputFormat.setIndent("	");// 以TAB方式实现缩进
        outputFormat.setNewlines(true);// 设置是否换行
        synchronized (document) {
            XMLWriter xmlWriter = new XMLWriter(out, outputFormat);
            xmlWriter.write(document);
            xmlWriter.close();
        }
    }
}
